# !/usr/bin/env python
# -*- coding:utf-8 -*-

import json

import requests
from bottle import Bottle, request, response, template, redirect

from conn.MyLogs import MyLogs
from conn.MyPagerFactory import MyPager
from conn.MySqlFactory import MySqlConfig
from schedu.ScheduleService import ScheduleService, Schedule

schedu = Bottle()
_sql = MySqlConfig('172.17.0.9', 'tuut', 'tuut', 'qrtz', 33069)
schedu_conn = _sql.conn()

@schedu.hook('before_request')
def validate():
    REQUEST_METHOD = request.environ.get('REQUEST_METHOD')
    HTTP_ACCESS_CONTROL_REQUEST_METHOD = request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
    if REQUEST_METHOD == 'OPTIONS' and HTTP_ACCESS_CONTROL_REQUEST_METHOD:
        request.environ['REQUEST_METHOD'] = HTTP_ACCESS_CONTROL_REQUEST_METHOD


@schedu.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'  # 允许所有域名的请求
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, DELETE, PUT, HEAD, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'origin,content-type,accept,authorization,x-requested-with'
    response.headers["Access-Control-Allow-Credentials"] = "true"
    response.headers['Access-Control-Max-Age'] = 86400
    response.status = 200

# 定时任务业务
class ScheduleRoute:
    # base_link_url = 'http://172.17.0.9:4001/job'
    base_link_url = ''

    ERROR_CODE = {
        "100": "任务名称重复，数据添加失败",
        "101": "任务名称错误，请重新输入",
        "102": "任务名称不存在，数据更新失败",
        "103": "任务名称不存在，数据删除失败",
        "104": "任务数据后台停止失败，请检查服务端日志",
        "105": "任务数据后台恢复失败，请检查服务端日志",
        "106": "任务数据后台激活失败，请检查服务端日志",
        "109": "任务名称不存在，数据处理失败",
    }

    @staticmethod
    @schedu.get('/')
    def index():
        errMsg = request.params.errMsg
        _url = ScheduleRoute.base_link_url + '/queryjobApi?jobName=\'\''
        _pages = MyPager.make_pager('schedu', [], 100, single_pager=True)
        _chooseData = ScheduleService.get_schedus("")
        try:
            if len(errMsg) > 0:
                return template('schedus.html', pages=_pages, chooseData=_chooseData,
                                errMsg=ScheduleRoute.ERROR_CODE[errMsg])

            res = requests.get(url=_url)
            if res.status_code == 200:
                datas_json = json.loads(res.text)
                _pages = MyPager.make_pager('schedu', datas_json['data'], 100, single_pager=True)
                return template('schedus.html', pages=_pages, chooseData=_chooseData, errMsg='')
            else:
                return template('schedus.html', pages=_pages, chooseData=_chooseData, errMsg=res.text)
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
            return template('schedus.html', pages=_pages, chooseData=_chooseData,
                            errMsg="任务服务未能正常启动连接，请检查网络或服务是否正常。\n%s" % e)

    @staticmethod
    @schedu.get('/fetch')
    def fetchtr():
        job_name = request.params.jobName
        _url = ScheduleRoute.base_link_url + '/queryjobApi?jobName=%s' % job_name
        res = requests.get(url=_url)
        datas_json = json.loads(res.text)
        _pages = MyPager.make_pager('schedu', datas_json['data'], 100, single_pager=True)
        _chooseData = ScheduleService.get_schedus("")
        return template('schedus.html', pages=_pages, chooseData=_chooseData, errMsg='')

    @staticmethod
    @schedu.get('/one')
    def infor():
        job_name = request.params.jobName
        _chooseData = ScheduleService.get_schedus(job_name)
        return {'code': 200, 'data': _chooseData['data'][0], 'msg': ''}

    @staticmethod
    @schedu.get('/oneApi')
    def infoApi():
        job_name = request.params.jobName
        _url = ScheduleRoute.base_link_url + '/queryjobApi?jobName=%s' % job_name
        res = requests.get(url=_url)
        datas_json = json.loads(res.text)
        return {'code': 200, 'data': datas_json['data'][0], 'msg': ''}

    @staticmethod
    @schedu.post('/handleAdd')
    def handle_add():
        _pages = MyPager.make_pager('schedu', [], 100, single_pager=True)
        job_name = request.forms.jobName
        job_group_name = request.forms.jobGroupName
        job_class = request.forms.jobClass
        trigger_name = request.forms.triggerName
        trigger_group_name = request.forms.triggerGroupName
        cron_expression = request.forms.cronExpression
        call_back = request.forms.callBack
        if len(job_name) == 0:
            # return template('schedus.html', pages=_pages, errMsg='任务名称错误，请重新输入')
            return redirect("/schedu/?errMsg=101")
        _sql_str = "SELECT count(1) FROM QRTZ_JOB_DETAILS WHERE job_name = '%s'" % job_name
        data_list = MySqlConfig.sql_execute(_sql, _sql_str)
        if data_list[0][0] == 0:
            schedule = Schedule(job_name, job_group_name, job_class,
                                trigger_name, trigger_group_name, cron_expression, call_back)
            ScheduleService.add_schedu(schedule)
            ScheduleRoute.handle_client_push(schedule)
            return redirect("/schedu/")
        else:
            return redirect("/schedu/?errMsg=100")

    @staticmethod
    def handle_client_push(schedule):
        _obj = {"jobName": schedule.job_name, "jobGroupName": schedule.job_group_name, "jobClass": schedule.job_class,
                "triggerName": schedule.trigger_name, "triggerGroupName": schedule.trigger_group_name,
                "cronExpression": schedule.cron_expression, "callBack": schedule.call_back}
        res = requests.post(url=ScheduleRoute.base_link_url + '/addjob', data=json.dumps(_obj),
                            headers={'Content-Type': 'application/json'})
        if res.status_code == 200:
            MyLogs.logger.info("定时任务数据添加成功")
        else:
            MyLogs.logger.error("任务数据后台添加失败，请检查服务端日志")

    @staticmethod
    @schedu.put('/handleUpdate')
    def handle_update():
        _pages = MyPager.make_pager('schedu', [], 100, single_pager=True)
        job_name = request.forms.jobName
        job_group_name = request.forms.jobGroupName
        job_class = request.forms.jobClass
        trigger_name = request.forms.triggerName
        trigger_group_name = request.forms.triggerGroupName
        cron_expression = request.forms.cronExpression
        call_back = request.forms.callBack
        if len(job_name) == 0:
            return redirect("/schedu/?errMsg=101")

        _sql_str = "SELECT count(1) FROM QRTZ_JOB_DETAILS WHERE job_name = '%s'" % job_name
        data_list = MySqlConfig.sql_execute(_sql, _sql_str)
        if data_list[0][0] > 0:
            schedule = Schedule(job_name, job_group_name, job_class,
                                trigger_name, trigger_group_name, cron_expression, call_back)
            ScheduleRoute.handle_client_reset(schedule)
            return {'code': 200, 'data': {}, 'msg': ''}
        else:
            return redirect("/schedu/?errMsg=102")

    @staticmethod
    def handle_client_reset(schedule):
        _obj = {"jobName": schedule.job_name, "jobGroupName": schedule.job_group_name,
                "jobClass": schedule.job_class,
                "triggerName": schedule.trigger_name, "triggerGroupName": schedule.trigger_group_name,
                "cronExpression": schedule.cron_expression, "callBack": schedule.call_back}
        res = requests.post(url=ScheduleRoute.base_link_url + '/reschedulejob', data=json.dumps(_obj),
                            headers={'Content-Type': 'application/json'})
        if res.status_code == 200:
            MyLogs.logger.info("定时任务数据更新成功")
        else:
            MyLogs.logger.error("任务数据后台更新失败，请检查服务端日志")

    @staticmethod
    @schedu.put('/handleDelete')
    def handle_delete():
        _pages = MyPager.make_pager('schedu', [], 100, single_pager=True)
        job_name = request.forms.jobName
        if len(job_name) == 0:
            return redirect("/schedu/?errMsg=101")

        _sql_str = "SELECT count(1) FROM QRTZ_JOB_DETAILS WHERE job_name = '%s'" % job_name
        data_list = MySqlConfig.sql_execute(_sql, _sql_str)
        if data_list[0][0] > 0:
            ScheduleRoute.handle_client_delete()
            return {'code': 200, 'data': {}, 'msg': ''}
        else:
            return redirect("/schedu/?errMsg=103")

    @staticmethod
    def handle_client_delete():
        _pages = MyPager.make_pager('schedu', [], 100, single_pager=True)
        job_name = request.forms.jobName
        job_group_name = request.forms.jobGroupName
        _obj = {"jobName": job_name, "jobGroupName": job_group_name}
        res = requests.post(url=ScheduleRoute.base_link_url + '/deletejob', data=json.dumps(_obj),
                            headers={'Content-Type': 'application/json'})
        if res.status_code == 200:
            MyLogs.logger.info("定时任务数据删除成功")
        else:
            MyLogs.logger.error("任务数据后台删除失败，请检查服务端日志")

    # 暂停任务 #
    @staticmethod
    @schedu.put('/handlePause')
    def handle_pause():
        _pages = MyPager.make_pager('schedu', [], 100, single_pager=True)
        job_name = request.forms.jobName
        job_group_name = request.forms.jobGroupName
        if len(job_name) == 0:
            return redirect("/schedu/?errMsg=101")

        _sql_str = "SELECT count(1) FROM QRTZ_JOB_DETAILS WHERE job_name = '%s'" % job_name
        data_list = MySqlConfig.sql_execute(_sql, _sql_str)
        if data_list[0][0] > 0:
            _obj = {"jobName": job_name, "jobGroupName": job_group_name}
            res = requests.post(url=ScheduleRoute.base_link_url + '/pausejob', data=json.dumps(_obj),
                                headers={'Content-Type': 'application/json'})
            if res.status_code == 200:
                return json.dumps({"code": res.status_code, "errMsg": '', "data": ''})
            else:
                return redirect("/schedu/?errMsg=104")
        else:
            return redirect("/schedu/?errMsg=109")

    # 恢复任务 #
    @staticmethod
    @schedu.put('/handleResume')
    def handle_resume():
        _pages = MyPager.make_pager('schedu', [], 100, single_pager=True)
        job_name = request.forms.jobName
        job_group_name = request.forms.jobGroupName
        if len(job_name) == 0:
            return redirect("/schedu/?errMsg=101")

        _sql_str = "SELECT count(1) FROM QRTZ_JOB_DETAILS WHERE job_name = '%s'" % job_name
        data_list = MySqlConfig.sql_execute(_sql, _sql_str)
        if data_list[0][0] > 0:
            _obj = {"jobName": job_name, "jobGroupName": job_group_name}
            res = requests.post(url=ScheduleRoute.base_link_url + '/resumejob', data=json.dumps(_obj),
                                headers={'Content-Type': 'application/json'})
            if res.status_code == 200:
                return json.dumps({"code": res.status_code, "errMsg": '', "data": ''})
            else:
                return redirect("/schedu/?errMsg=105")
        else:
            return redirect("/schedu/?errMsg=109")

    # 更新激活时间 #
    @staticmethod
    @schedu.put('/handleRef')
    def handle_ref():
        _pages = MyPager.make_pager('schedu', [], 100, single_pager=True)
        job_name = request.forms.jobName
        job_group_name = request.forms.jobGroupName
        if len(job_name) == 0:
            return redirect("/schedu/?errMsg=101")

        _sql_str = "SELECT count(1) FROM QRTZ_JOB_DETAILS WHERE job_name = '%s'" % job_name
        data_list = MySqlConfig.sql_execute(_sql, _sql_str)
        if data_list[0][0] > 0:
            _obj = {"jobName": job_name, "jobGroupName": job_group_name}
            res = requests.post(url=ScheduleRoute.base_link_url + '/refreshjob', data=json.dumps(_obj),
                                headers={'Content-Type': 'application/json'})
            if res.status_code == 200:
                return json.dumps({"code": res.status_code, "errMsg": '', "data": ''})
            else:
                return redirect("/schedu/?errMsg=106")
        else:
            return redirect("/schedu/?errMsg=109")
